import { Component } from "react";
import Books from "./books.json";
import { Homepage } from "../App";
import "./TBooks.css";
import SLM from "./slm/SLM";
import MLInAction from "./ml-in-action/MLInAction";

const PageTitle = '书局';

export default
class TBooks extends Component{
  constructor(props){
    super(props);

    this.state={
      pageName      : 'index',
      bookList      : [],    // 书籍列表
      selectedIndex : -1 ,   // 选中书籍索引值

      // 书籍显示
      coverWidth    : 124,
      coverHeight   : 245,
    }

    this.handleBookChanged = this.handleBookChanged.bind(this);

    this.refresh = this.refresh.bind(this);
  }

  componentDidMount(){
    document.title =  `T+藏宝馆-${PageTitle}`;
    this.refresh();
  }

  handleBookChanged(event){
    const book = this.state.bookList[event.target.id];
    document.title = `T+藏宝馆-${PageTitle}:${book.bookName}`;

    this.setState({
      pageName : book.bookId,
    })
  }

  refresh(){
    // 从books.json中读取书籍列表
    let bookList = [];
    let selectedIndex = -1;
    for(let bookId in Books){
      bookList.push(Books[bookId]);
    }
    if(bookList.length > 0) selectedIndex = 0;

    this.setState({
      bookList      : bookList,
      selectedIndex : selectedIndex
    })
  }

  // 渲染书籍列表
  _renderBooks(){
    const bookList      = this.state.bookList;
    // const selectedIndex = this.state.selectedIndex;

    return bookList.map((item, key)=>
      <div className="book" key={key}>
        <img src={`/${Homepage}/${item.bookCover}`} 
          alt={`/${Homepage}/${item.bookCover}`}>
        </img>
        <button id={key} onClick={this.handleBookChanged}>{item.bookName}</button>
      </div>
    );
  }

  // 显示主页
  homepage(){
    document.title =  `T+藏宝馆-${PageTitle}`;
    this.refresh();

    this.setState({ pageName:'index' });
  }

  _home(){
    return(
    <div className="body">
      <div>
        <button className='hlink' onClick={this.props.home}>T<sup>+</sup>藏宝馆:</button>
        <button className='hlink' onClick={this.refresh}>{`${PageTitle}`}</button>
      </div>
      <div className="book-list">
        {this._renderBooks()}
      </div>
    </div>
    );
  }

  render(){
    switch(this.state.pageName){
      case 'index'    : return this._home();
      case 'SLM'      : return <SLM home={this.homepage.bind(this)}/>;
      case 'ML_IN_ACTION' : return <MLInAction home={this.homepage.bind(this)}/>;
      default         : return this._home();
    }
  }
}